<template>
	<view>
		<u-popup v-model="value" mode="center" :popup="false" @close="close">
			<view class="payment" :style="[{ height: paytypelist.length == 2 ? '670rpx' : '570rpx' }]">
				<view class="header u-flex u-row-between u-p-l-30 u-p-r-30 u-p-t-20 u-p-b-20">
					<view class="">{{ title }}</view>
					<u-icon name="close" @click="close"></u-icon>
				</view>
				<view class="u-p-30">
					<view class="alert-warning u-p-20 u-m-b-10">
						<view class="">{{ desc }}</view>
						<view class="price u-m-t-10">充值金额：￥{{ money }}</view>
					</view>

					<view class="u-border-top u-m-t-20">
						<u-radio-group v-model="paytype" class="group">
							<view class="group" v-for="(item, index) in paytypelist" :key="index">
								<u-cell-item :icon="item.icon" :icon-style="item.iconColor" :arrow="false" :title="item.name" @click="selectType(item.value)">
									<u-radio slot="right-icon" :active-color="theme.bgColor" label-size="30" :name="item.value">
										<u-icon size="30" name="arrow-right"></u-icon>
									</u-radio>
								</u-cell-item>
							</view>
						</u-radio-group>
					</view>
				</view>
				<view class="u-text-center u-p-30">
					<u-button
						type="primary"
						hover-class="none"
						:custom-style="{ width: '80%', height: '60rpx', backgroundColor: theme.bgColor, color: theme.color }"
						size="mini"
						@click="submit"
					>
						立即支付
					</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { login } from '@/common/fa.mixin.js';
export default {
	mixins: [login],
	props: {
		value: {
			type: Boolean,
			default: false
		},
		title: {
			type: String,
			default: '立即充值'
		},
		desc: {
			type: String,
			default: '您的余额不足，无法设定付费或邀请赏金，请先充值！'
		},
		money: {
			type: [String, Number],
			default: 0
		}
	},
	computed: {
		paytypelist() {			
			let list = [{
					name: '微信支付',
					value: 'wechat',
					icon: 'weixin-circle-fill',
					iconColor: { color: '#40BA49' }
				}];
				
			// #ifdef APP-PLUS || MP-ALIPAY 
				list.push({
					name: '支付宝支付',
					value: 'alipay',
					icon: 'zhifubao-circle-fill',
					iconColor: { color: '#00AAEE' }
				});		
			// #endif			
			// #ifdef H5			
				if (!this.$util.isWeiXinBrowser()) {
					list.push({
						name: '支付宝支付',
						value: 'alipay',
						icon: 'zhifubao-circle-fill',
						iconColor: { color: '#00AAEE' }
					});
				}			
			// #endif
			return list;
		}
	},
	data() {
		return {
			isShow: false,
			paytype: 'wechat'
		};
	},
	methods: {
		close() {
			this.$emit('input', false);
		},
		selectType(type) {
			this.paytype = type;
		},
		// #ifndef H5
		async submit() {
			
			let data = {
				money: this.money,
				paytype: this.paytype
			}
			
			// #ifdef APP-PLUS
				data.appid = plus.runtime.appid;
				data.method = 'app';
			// #endif
			
			// #ifdef MP-WEIXIN
				data.method = 'miniapp';
			// #endif
			
			let res = await this.$api.goRechargeSubmit(data);
			if(res.data=='bind'){
				// #ifdef MP-WEIXIN
				this.$wanlshop.to('/pages/community/login/wxlogin');
				// #endif				
				return;
			}
			if(!res.code){
				this.$u.toast(res.msg);
				return;
			 }
			
			// #ifdef MP-WEIXIN
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: res.data.timeStamp,
					nonceStr: res.data.nonceStr,
					package: res.data.package,
					signType: res.data.signType,
					paySign: res.data.paySign,
					success: res => {
						this.$u.toast('充值成功！');
						this.$emit('paySuccess');
					},
					fail: err => {
						this.$u.toast('fail:' + JSON.stringify(err));
					}
				});
			// #endif
			
			// #ifdef APP-PLUS
				uni.requestPayment({
				    provider: this.paytype=='alipay'?'alipay':'wxpay',
				    orderInfo: res.data, //微信、支付宝订单数据
				    success: res =>{
				        this.$u.toast('支付成功！');
				        this.$emit('paySuccess');
				    },
				    fail: function (err) {
				        console.log('fail:' + JSON.stringify(err));
				    }
				});
			// #endif
		
		},
		// #endif
		
		// #ifdef H5
			async submit() {				

				let data = {
					money: this.money,
					paytype: this.paytype,
					method: 'wap'
				};
				//在微信环境，且为微信支付
				if (this.$util.isWeiXinBrowser() && this.paytype == 'wechat') {
					data.method = 'mp';
					let res = await this.$api.goRechargeSubmit(data);
					if(res.data=='bind'){
						this.goToAuth();
						return;
					}
					if(!res || !res.code){
						this.$u.toast(res.msg || '支付错误');
						return;
					 }					
					window.WeixinJSBridge.invoke(
						'getBrandWCPayRequest',
						{
							appId: res.data.appId, // 公众号名称，由商户传入
							timeStamp: res.data.timeStamp, // 时间戳，自1970年以来的秒数
							nonceStr: res.data.nonceStr, // 随机串
							package: res.data.package,
							signType: res.data.signType, // 微信签名方式：
							paySign: res.data.paySign // 微信签名
						},
						res => {
							if (res.err_msg === 'get_brand_wcpay_request:ok') {
								this.$u.toast('充值成功！');
								this.$emit('paySuccess');
							} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
								this.$u.toast('取消支付');
							} else {
								this.$u.toast('支付失败');
							}
						}
					);
				} else {
					//非微信环境的wap 支付方法，会返回orderid，再模拟表单提交
					data.returnurl = window.location.href;
					let res = await this.$api.goRechargeSubmit(data);				
					if (!res || !res.code) {
						this.$u.toast(res.msg || '支付错误！');
						return;
					};
		
					//URL地址
					if(res.data.toString().match(/^((?:[a-z]+:)?\/\/)(.*)/i)){
						location.href = res.data;
						return;
					}
		
					//Form表单
					document.getElementsByTagName("body")[0].innerHTML = res.data;
					let form = document.querySelector("form");
					if(form && form.length>0){
						form.submit();
						return;
					}
		
					//Meta跳转
					let meta = document.querySelector('meta[http-equiv="refresh"]');
					if(meta && meta.length>0){
						setTimeout(function(){
							location.href = meta.content.split(/;/)[1];
						}, 300);
						return;
					}
				}
			}
		// #endif
	}
};
</script>

<style lang="scss" scoped>
.payment {
	width: 600rpx;

	.header {
		border-bottom: 1px solid #eee;
		background-color: #f8f8f8;
	}

	.alert-info {
		background-color: #d9edf7;
		border-color: #bce8f1;
		color: #3498db;
		border-radius: 6rpx;
	}

	.alert-warning {
		background-color: #fcf8e3;
		border-color: #faebcc;
		color: #f39c12;
		border-radius: 6rpx;
	}
	.price {
		color: red;
	}
	.group {
		width: 100%;
	}
}
</style>
